package com.yanqu.road.server.gameplayer.module.activity.flowerstudy;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.ActivityRewardResult;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.activity.args.FlowerStudyRankArgs;
import com.yanqu.road.entity.activity.flowerstudy.config.FlowerStudyConfig;
import com.yanqu.road.entity.activity.flowerstudy.config.FlowerStudyVisitConfig;
import com.yanqu.road.entity.activity.flowerstudy.data.FlowerStudyUserData;
import com.yanqu.road.entity.activity.flowerstudy.data.FlowerStudyUserWarReport;
import com.yanqu.road.entity.enums.activity.flowerstudy.eFlowerStudyPeriodType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.logic.bussiness.activity.FlowerStudyBusiness;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.FlowerStudyProto;
import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityModule;
import com.yanqu.road.server.gameplayer.module.banquet.BanquetModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.DecorationModule;
import com.yanqu.road.server.logic.activity.BaseActivityData;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.flowerstudy.FlowerStudyMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class FlowerStudyModule extends GeneralModule {

    private FlowerStudyUserData userData;

    private List<FlowerStudyUserWarReport> reportList = new ArrayList<>();

    private List<FlowerStudyUserWarReport> needSaveReportList = new ArrayList<>();

    private long lastMoveTime = 0;

    public FlowerStudyModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (ActivityMgr.activityInShowTime(activityInfo)){
            userData = FlowerStudyBusiness.getFlowerStudyUserData(activityInfo.getActivityId(),getUserId());
            reportList = FlowerStudyBusiness.getFlowerStudyUserWarReportList(activityInfo.getActivityId(),getUserId());
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData != null){
            if (userData.isInsertOption()){
                FlowerStudyBusiness.addFlowerStudyUserData(userData);
            }else if (userData.isUpdateOption()){
                FlowerStudyBusiness.updateFlowerStudyUserData(userData);
            }
        }
        if (!needSaveReportList.isEmpty()){
            List<FlowerStudyUserWarReport> tempDataList = new ArrayList<>(needSaveReportList);
            needSaveReportList.clear();
            FlowerStudyBusiness.addFlowerStudyUserWarReportList(tempDataList);
        }

        return true;
    }

    @Override
    public void afterLogin() {
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            return;
        }
        if (!ActivityMgr.activityInShowTime(activityInfo)){
            return;
        }

        syncConfig();
        syncUserData();
        checkPoemRefresh();
        checkVisitRefresh();
    }

    /**
     * 活动奖励返回
     */
    public ActivityRewardResult dealNewCrossRankActivityReward(int activityId ,int conditionId ,int myRank){
        ActivityRewardResult result = new ActivityRewardResult();
        ActivityModule module = player.getModule(ActivityModule.class);
        BaseActivityData baseActivityData = module.getBaseActivityData(activityId);
        if (null == baseActivityData) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
        if(null == activityInfo){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        ActivityConditionInfo activityConditionInfo = NormalActivityMgr.getActivityConditionInfo(activityId, conditionId);
        if(null == activityConditionInfo){
            result.setRet(GameErrorCode.E_ACTIVITY_GET_REWARD_CONDITION_ERROR);
            return result;
        }
        UserActivityConditionData userActivityConditionData = baseActivityData.getUserActivityConditionData(conditionId);
        if(null == userActivityConditionData){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_JOIN);
            return result;
        }
        if (userActivityConditionData.isGetReward()) {
            result.setRet(GameErrorCode.E_ACTIVITY_REWARD_IS_GET);
            return result;
        }
        FlowerStudyConfig config = FlowerStudyMgr.getConfig();
        if (config == null){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }

        Date now = new Date();
        //乡试
        if (activityConditionInfo.getType() == eGamePlayerEventType.FlowerStudyScoreLocalRankCondition.getValue()){
            if (now.before(config.getLocalExamEndDate())){
                result.setRet(GameErrorCode.E_ACTIVITY_NO_IN_GET_REWARD_TIME);
                return result;
            }
        }
        //省
        if (activityConditionInfo.getType() == eGamePlayerEventType.FlowerStudyScoreProvinceRankCondition.getValue()){
            if (now.before(config.getProvincialExamEndDate())){
                result.setRet(GameErrorCode.E_ACTIVITY_NO_IN_GET_REWARD_TIME);
                return result;
            }
        }
        //殿试
        if (activityConditionInfo.getType() == eGamePlayerEventType.FlowerStudyScorePalaceRankCondition.getValue()){
            if (now.before(config.getPalaceExamEndDate())){
                result.setRet(GameErrorCode.E_ACTIVITY_NO_IN_GET_REWARD_TIME);
                return result;
            }
        }
        ActivityConditionInfo conditionInfo = NormalActivityMgr.getActivityConditionInfoByRankAndType(activityId, activityConditionInfo.getType(), myRank);
        if(null == conditionInfo) {
            result.setRet(GameErrorCode.E_ACTIVITY_CONDITION_NO_COMPLETE);
            return result;
        }
        //添加奖励
        module.startChanges();
        userActivityConditionData.setGetReward(true);
        userActivityConditionData.setModifyTime(System.currentTimeMillis() / 1000);
        baseActivityData.finish(userActivityConditionData.getConditionId());
        player.getModule(CurrencyModule.class).addCurrency(conditionInfo.getReward(), eLogMoneyType.Activity, eLogMoneyType.CrossActivityReward);
        result.setReward(conditionInfo.getRewardStr());
        //记录跨服称号包含的区服id
        conditionInfo.getReward().getGoods().forEach((k,v)->{
            if (GoodsMgr.isDecorationGoods(k)) {
                player.getModule(DecorationModule.class).setServerIds(k, activityInfo.getActivityId(), activityInfo.getServerListStr());
            }
        });
        player.getModule(BanquetModule.class).getCrossBanquetInvitationReward(conditionInfo.getRewardStr(), activityInfo.getServerListStr());

        LogMgr.addLogActivityReward(player.getUserId(), activityId, activityInfo.getType(), activityInfo.getChildType(),
                activityConditionInfo.getConditionId(), myRank, false, result.getReward());
        module.onActivityDataChanged(baseActivityData);
        module.finishChanges();
        return result;


    }

    /**
     * 领取活动奖励
     */
    public ActivityRewardResult getNewCrossRankActivityReward(int activityId, int conditionId) {
        ActivityRewardResult result = new ActivityRewardResult();
        BaseActivityData baseActivityData = player.getModule(ActivityModule.class).getBaseActivityData(activityId);
        if (null == baseActivityData) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
        if(null == activityInfo){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        ActivityConditionInfo activityConditionInfo = NormalActivityMgr.getActivityConditionInfo(activityId, conditionId);
        if(null == activityConditionInfo){
            result.setRet(GameErrorCode.E_ACTIVITY_GET_REWARD_CONDITION_ERROR);
            return result;
        }
        UserActivityConditionData userActivityConditionData = baseActivityData.getUserActivityConditionData(conditionId);
        if(null == userActivityConditionData){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_JOIN);
            return result;
        }
        if (userActivityConditionData.isGetReward()) {
            result.setRet(GameErrorCode.E_ACTIVITY_REWARD_IS_GET);
            return result;
        }
        FlowerStudyConfig config = FlowerStudyMgr.getConfig();
        if (config == null){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }

        Date now = new Date();
        //乡试
        if (activityConditionInfo.getType() == eGamePlayerEventType.FlowerStudyScoreLocalRankCondition.getValue()){
            if (now.before(config.getLocalExamEndDate())){
                result.setRet(GameErrorCode.E_ACTIVITY_NO_IN_GET_REWARD_TIME);
                return result;
            }
        }
        //省
        if (activityConditionInfo.getType() == eGamePlayerEventType.FlowerStudyScoreProvinceRankCondition.getValue()){
            if (now.before(config.getProvincialExamEndDate())){
                result.setRet(GameErrorCode.E_ACTIVITY_NO_IN_GET_REWARD_TIME);
                return result;
            }
        }
        //殿试
        if (activityConditionInfo.getType() == eGamePlayerEventType.FlowerStudyScorePalaceRankCondition.getValue()){
            if (now.before(config.getPalaceExamEndDate())){
                result.setRet(GameErrorCode.E_ACTIVITY_NO_IN_GET_REWARD_TIME);
                return result;
            }
        }
        CrossActivityProto.CrossActivityGetRewardReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityGetRewardReqMsg.newBuilder();
        reqMsg.setActivityId(activityId);
        reqMsg.setConditionId(userActivityConditionData.getConditionId());
        YanQuMessage pkg = YanQuMessageUtils.buildMessage(Protocol.C_FLOWER_STUDY_CROSS_ACTIVITY_GET_RANK_REWARD, reqMsg);
        GamePlayerMgr.sendPacket(player.getUserId(), pkg);
        return result;
    }


    /**
     * 开始匹配
     */
    public int startMatching(int activityId,int roomType) {
        int ret = simpleCheck(activityId);
        if (ret != 0) {
            return ret;
        }
        if (userData == null || userData.getActivityId() != activityId){
            initUserData();
        }
        if (userData == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }
        FlowerStudyConfig config = FlowerStudyMgr.getConfig();
        int examNowPeriod = config.getExamNowPeriod();
        if (roomType == 1 && examNowPeriod != eFlowerStudyPeriodType.openLocal.getValue()){
            return GameErrorCode.E_FLOWER_STUDY_CROSS_ACTIVITY_LOCAL_EXAM_NO_OPEN;
        }
        if (roomType == 2 && examNowPeriod != eFlowerStudyPeriodType.openProvincial.getValue()){
            return GameErrorCode.E_FLOWER_STUDY_CROSS_ACTIVITY_PROVINCE_EXAM_NO_OPEN;
        }
        if (roomType == 3 && examNowPeriod != eFlowerStudyPeriodType.openPalace.getValue()){
            return GameErrorCode.E_FLOWER_STUDY_CROSS_ACTIVITY_PALACE_EXAM_NO_OPEN;
        }else if (roomType != 1 && roomType != 2 && roomType != 3){
            return GameErrorCode.E_ERROR_PARAMETER;
        }

        FlowerStudyProto.CrossFlowerStudyExamMatchingStartReq.Builder msg = FlowerStudyProto.CrossFlowerStudyExamMatchingStartReq.newBuilder();
        msg.setActivityId(activityId);
        msg.setRoomType(roomType);
        msg.setUserBaseInfo(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
        player.sendPacket(CrossProtocol.C_FLOWER_STUDY_EXAM_START_MATCHING, msg);

        return 0;
    }

    /**
     * 分享领奖
     */
    public int getShareReward(int activityId){
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }
        if (activityInfo.getActivityId() != activityId){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_ID_ERROR;
        }
        if (userData == null || userData.getActivityId() != activityId){
            initUserData();
        }
        if (userData == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }
        FlowerStudyConfig config = FlowerStudyMgr.getConfig();
        if (config == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_CONFIG_ERROR;
        }

        if (userData.getHasShare() == 1){
            return GameErrorCode.E_FLOWER_STUDY_SHARE_REWARD_ALREADY_GET;
        }
        String shareReward = config.getShareReward();
        userData.setHasShare(1);
        player.getModule(CurrencyModule.class).addCurrency(shareReward,eLogMoneyType.FlowerStudy,eLogMoneyType.FlowerStudyShareGet);

        FlowerStudyProto.FlowerStudyShareGetRewardResp.Builder builder = FlowerStudyProto.FlowerStudyShareGetRewardResp.newBuilder();
        builder.setRet(0);
        builder.setReward(shareReward);
        player.sendPacket(ClientProtocol.U_FLOWER_STUDY_SHARE_GET_REWARD,builder);
        syncUserData();
        return 0;
    }


    /**
     * 同步配置
     */

    public void syncConfig() {
        FlowerStudyProto.FlowerStudyConfigSync.Builder msg = FlowerStudyMgr.getFlowerStudyConfigMsg(player.getLanguage());
        if (msg != null) {
            player.sendPacket(ClientProtocol.U_FLOWER_STUDY_CONFIG_SYNC, msg);
        }
    }

    /**
     * 获取名人来访奖励
     * @param activityId
     * @return
     */

    public int getVisitManReward(int activityId) {
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }
        if (activityInfo.getActivityId() != activityId){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_ID_ERROR;
        }
        if (userData == null || userData.getActivityId() != activityId){
            initUserData();
        }
        if (userData == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }

        checkVisitRefresh();
        if (userData.getVisitManOpCount()>0){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_VISIT_NPC_HAS_OPERATE;
        }
        if (userData.getVisitManId() == 0){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_VISIT_NPC_NO_INIT;
        }
        FlowerStudyVisitConfig visitConfigById = FlowerStudyMgr.getVisitConfigById(userData.getVisitManId());
        if (visitConfigById == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_CONFIG_ERROR;
        }

        userData.setVisitManOpCount(1);
        Property property = PropertyHelper.parseNewStringToProperty(visitConfigById.getReward());
        player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.FlowerStudy,eLogMoneyType.FlowerStudyVisitManGet);

        FlowerStudyProto.FlowerStudyVisitResp.Builder msg = FlowerStudyProto.FlowerStudyVisitResp.newBuilder();
        msg.setRet(0);
        msg.setReward(PropertyHelper.parsePropertyToString(property));
        msg.setUserData(parseFlowerStudyUserDataToMsg());
        player.sendPacket(ClientProtocol.U_FLOWER_DEAL_VISIT, msg);

        return 0;
    }

    /**
     * 同步玩家数据
     */
    public void syncUserData(){
        if (userData == null){
            initUserData();
        }
        if (userData == null){
            return;
        }
        FlowerStudyProto.FlowerStudyUserDataMsg.Builder builder = parseFlowerStudyUserDataToMsg();
        player.sendPacket(ClientProtocol.U_FLOWER_STUDY_DATA_SYNC,builder);
    }

    /**
     * 诗书问答提交答案
     */
    public int poemSubmitAnswer(int activityId){
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }
        if (activityInfo.getActivityId() != activityId){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_ID_ERROR;
        }
        if (userData == null || userData.getActivityId() != activityId){
            initUserData();
        }
        if (userData == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }

        if (userData.getPoemIsSubmitted() >= 1){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_POEM_HAS_SUBMIT;
        }

        if (userData.getPoemRecord().containsValue(0)){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_POEM_HAS_NO_CHOOSE;
        }
        userData.setPoemIsSubmitted(1);
        userData.setPoemTodayFinishCount(userData.getPoemTodayFinishCount()+1);
        player.notifyListener(eGamePlayerEventType.FlowerStudyQACondition.getValue(),1);

        FlowerStudyProto.FlowerStudyPoemSubmitResp.Builder msg = FlowerStudyProto.FlowerStudyPoemSubmitResp.newBuilder();
        msg.setRet(0);
        msg.setUserData(parseFlowerStudyUserDataToMsg());
        player.sendPacket(ClientProtocol.U_FLOWER_STUDY_COMMIT_ANSWER,msg);
        return 0;
    }


    /**
     * 诗书问答选择题目
     */
    public int choosePoemAnswer(int activityId,int questionId,int choose){
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }
        if (activityInfo.getActivityId() != activityId){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_ID_ERROR;
        }
        if (userData == null || userData.getActivityId() != activityId){
            initUserData();
        }
        if (userData == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }
        checkPoemRefresh();
        if(!userData.getPoemRecord().containsKey(questionId)){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_POEM_ID_NO_EXIST;
        }
        if (userData.getPoemIsSubmitted() == 1){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_POEM_HAS_SUBMIT;
        }
        userData.getPoemRecord().put(questionId,choose);
        userData.setUpdateOption();
        FlowerStudyProto.FlowerStudyPoemChooseResp.Builder msg = FlowerStudyProto.FlowerStudyPoemChooseResp.newBuilder();
        msg.setRet(0);
        for (Map.Entry<Integer,Integer> entry:userData.getPoemRecord().entrySet()){
            FlowerStudyProto.FlowerStudyPoemChooseData.Builder data = FlowerStudyProto.FlowerStudyPoemChooseData.newBuilder();
            data.setId(entry.getKey());
            data.setChoose(entry.getValue());
            msg.addChooseData(data);
        }
        player.sendPacket(ClientProtocol.U_FLOWER_STUDY_CHOOSE_POEM,msg);
        return 0;
    }

    /**
     * 检查每日诗书问答是否刷新
     */
    public void checkPoemRefresh(){
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            return;
        }

        if (userData == null){
            return;
        }
        long now = System.currentTimeMillis();
        if (!DateHelper.isSameDay(now/1000,userData.getPoemRefreshTime()/1000)){
            userData.setPoemRecord(FlowerStudyMgr.getRandomPoemMap());
            userData.setPoemRefreshTime(now);
            userData.setPoemTodayFinishCount(0);
            userData.setPoemIsSubmitted(0);
            syncUserData();
        }
    }

    /**
     * 检查每日名人来访是否刷新
     */
    public void checkVisitRefresh(){
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            return;
        }
        if (userData == null){
            return;
        }
        long now = System.currentTimeMillis();
        if (!DateHelper.isSameDay(now/1000,userData.getVisitManRefreshTime()/1000)){
            userData.setVisitManRefreshTime(now);
            userData.setVisitManId(FlowerStudyMgr.getRandomVisitManId());
            userData.setVisitManOpCount(0);
            syncUserData();
        }
    }

    /**
     * 基本判断
     * @param activityId
     * @return
     */
    public int simpleCheck(int activityId){
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }
        if (activityInfo.getActivityId() != activityId){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_ID_ERROR;
        }
        if (!ActivityMgr.activityInTime(activityInfo)){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }

        if (!SystemOpenMgr.systemOpen(player, eSystemId.FlowerStudy.getValue())){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_UNLOCK;
        }
        if( FlowerStudyMgr.getConfig() == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_CONFIG_ERROR;
        }
        if (userData == null || userData.getActivityId() != activityId){
            initUserData();
        }
        if (userData == null){
            return GameErrorCode.E_FLOWER_STUDY_ACTIVITY_NO_OPEN;
        }
        return 0;
    }

    public void initUserData(){
        FlowerStudyConfig config = FlowerStudyMgr.getConfig();
        if (config == null){
            return;
        }
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            return;
        }
        if (!SystemOpenMgr.systemOpen(player, eSystemId.FlowerStudy.getValue())){
            return;
        }

        if (userData != null && userData.getActivityId() == activityInfo.getActivityId()){
            return;
        }
        FlowerStudyUserData tmpFlowerStudyUserData = new FlowerStudyUserData();

        tmpFlowerStudyUserData.setActivityId(activityInfo.getActivityId());
        tmpFlowerStudyUserData.setUserId(getUserId());
        //-----------------------------名人来访-----------------
        tmpFlowerStudyUserData.setVisitManId(FlowerStudyMgr.getRandomVisitManId());
        tmpFlowerStudyUserData.setVisitManOpCount(0);
        tmpFlowerStudyUserData.setVisitManRefreshTime(System.currentTimeMillis());
        //-----------------------------诗书问答-----------------
        Map<Integer, Integer> randomPoemMap = FlowerStudyMgr.getRandomPoemMap();
        if (randomPoemMap == null){
            log.error("花城书房 randomPoemMap is null activityId:{}", activityInfo.getActivityId());
        }
        tmpFlowerStudyUserData.setPoemRecord(randomPoemMap);
        tmpFlowerStudyUserData.setPoemRefreshTime(System.currentTimeMillis());
        tmpFlowerStudyUserData.setPoemTodayFinishCount(0);
        tmpFlowerStudyUserData.setPoemIsSubmitted(0);
        tmpFlowerStudyUserData.setHasShare(0);
        tmpFlowerStudyUserData.setInsertOption();
        userData = tmpFlowerStudyUserData;

    }

    public FlowerStudyProto.FlowerStudyUserDataMsg.Builder parseFlowerStudyUserDataToMsg(){
        if (userData == null){
            return null;
        }
        FlowerStudyProto.FlowerStudyUserDataMsg.Builder builder = FlowerStudyProto.FlowerStudyUserDataMsg.newBuilder();

        if (userData.getPoemRecord() == null){   //如果没初始化
            userData.setPoemRecord(FlowerStudyMgr.getRandomPoemMap());
            userData.setVisitManId(FlowerStudyMgr.getRandomVisitManId());
        }
        builder.setVisitManId(userData.getVisitManId());
        builder.setVisitManOpCount(userData.getVisitManOpCount());
        for (Map.Entry<Integer,Integer> entry:userData.getPoemRecord().entrySet()){
            FlowerStudyProto.FlowerStudyPoemChooseData.Builder questionBuilder = FlowerStudyProto.FlowerStudyPoemChooseData.newBuilder();
            questionBuilder.setId(entry.getKey());
            questionBuilder.setChoose(entry.getValue());
            builder.addPoemQuestionRecord(questionBuilder);
        }
        builder.setPoemQuestionRefreshTime(userData.getPoemRefreshTime());
        builder.setPoemTodayFinishTime(userData.getPoemTodayFinishCount());
        builder.setPoemTodayIsSubmitted(userData.getPoemIsSubmitted());
        builder.setHasShare(userData.getHasShare());

        return builder;

    }



    /**
     * 处理跨服的同步事件
     */

    public void dealExamEventSync(FlowerStudyProto.FlowerStudyExamRoomDataSync msg){
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            log.error("花城书房 activityId dealExamEventSync activityInfo is null");
            return;
        }
        String reward = "";
        if (msg.hasReward()){
            reward = msg.getReward();
        }
        if (!StringUtils.isNullOrEmpty(reward)){
            player.getModule(CurrencyModule.class).addCurrency(reward,eLogMoneyType.FlowerStudy,eLogMoneyType.FlowerStudyExamReward);
        }
        addReport(msg.getRoomData(),reward);

        player.sendPacket(ClientProtocol.U_FLOWER_STUDY_EXAM_EVENT_SYNC, msg.toBuilder());
    }

    /**
     * 加战报
     * @param msg
     */

    public void addReport(FlowerStudyProto.FlowerStudyExamRoomData msg,String reward){
        FlowerStudyUserWarReport report = new FlowerStudyUserWarReport();
        int activityId = FlowerStudyMgr.getActivityInfo().getActivityId();
        report.setActivityId(activityId);
        report.setUserId(getUserId());
        report.setRoomId(msg.getRoomId());
        report.setRoomType(msg.getRoomType());
        report.setReward(reward);

        report.setSettlementTime(System.currentTimeMillis());

        List<FlowerStudyProto.FlowerStudyExamUserBattleData> userBattleDataList = msg.getUserBattleDataList();
        FlowerStudyProto.FlowerStudyExamUserBattleData myBattleData = null;
        for (FlowerStudyProto.FlowerStudyExamUserBattleData userBattleData: userBattleDataList){
            if (userBattleData.getUserId() == getUserId()){
                myBattleData = userBattleData;
            }
        }
        if (myBattleData == null){
            needSaveReportList.add(report);
            reportList.add(report);
            return;
        }

        int myRank = 1;
        for (FlowerStudyProto.FlowerStudyExamUserBattleData userBattleData: userBattleDataList){
            if (userBattleData.getUserId() != getUserId()){
                if (userBattleData.getScoreThisExam() > myBattleData.getScoreThisExam()){
                    myRank++;
                }if (userBattleData.getScoreThisExam() == myBattleData.getScoreThisExam()){
                    if (userBattleData.getTotalUseTime() <= myBattleData.getTotalUseTime()){
                        myRank++;
                    }
                }
            }
        }
        report.setRank(myRank);
        report.setScore(myBattleData.getScoreThisExam());
        report.setAnswerTime(myBattleData.getTotalUseTime());
        needSaveReportList.add(report);
        reportList.add(report);
        return;

    }
    /**
     * 处理跨服返回的匹配结果
     */
    public void dealMatchingResult(FlowerStudyProto.FlowerStudyExamMatchingStartResp resp){
        if (resp.getRet() != 0) {
            player.sendPacket(ClientProtocol.U_FLOWER_STUDY_EXAM_MATCHING_START, resp.toBuilder());
            return;
        }
        int roomType = resp.getRoomData().getRoomType();

        player.sendPacket(ClientProtocol.U_FLOWER_STUDY_EXAM_MATCHING_START, resp.toBuilder());

    }

    /**
     * 一答到底选择
     */
    public int chooseAnswer(FlowerStudyProto.FlowerStudyExamChooseReq req){
        int simpleCheck = simpleCheck(req.getActivityId());
        if (simpleCheck!=0){
            return simpleCheck;
        }
        long now = System.currentTimeMillis();
        if ((now - lastMoveTime )<200){
            return GameErrorCode.E_FLOWER_STUDY_MOVE_TOO_FAST;
        }
        lastMoveTime = now;
        player.sendPacket(CrossProtocol.C_FLOWER_STUDY_EXAM_CHOOSE_ANSWER, req.toBuilder());
        return 0;
    }

    public int quitRoom(FlowerStudyProto.FlowerStudyExamQuitRoomReq req){
        int simpleCheck = simpleCheck(req.getActivityId());
        if (simpleCheck!= 0){
            return simpleCheck;
        }
        player.sendPacket(CrossProtocol.C_FLOWER_STUDY_QUIT_ROOM, req.toBuilder());
        return 0;
    }

    public void dealQuitRoomResp(FlowerStudyProto.FlowerStudyExamQuitRoomResp resp){
        if (resp.getRet()!=0){
            player.sendPacket(ClientProtocol.U_FLOWER_STUDY_QUIT_ROOM, resp.toBuilder());
            return;
        }
        String reward ="";
        if (resp.hasReward()){
            reward = resp.getReward();
        }
        if (!StringUtils.isNullOrEmpty(reward)){
            player.getModule(CurrencyModule.class).addCurrency(reward,eLogMoneyType.FlowerStudy,eLogMoneyType.FlowerStudyExamReward);
        }
        addReport(resp.getRoomData(),reward);
        player.sendPacket(ClientProtocol.U_FLOWER_STUDY_QUIT_ROOM, resp.toBuilder());

    }



//    /**
//     * 增加今日一答到底次数
//     */
//    public void addTodayExamCount(int type){
//        if (userData == null){
//            return;
//        }
//        Map<Integer, Integer> todaySignUpCount = userData.getTodaySignUpCount();
//        if (todaySignUpCount == null){
//            userData.setTodaySignUpCount(new ConcurrentHashMap<>());
//            todaySignUpCount = userData.getTodaySignUpCount();
//        }
//        if (!todaySignUpCount.containsKey(type)){
//            todaySignUpCount.put(type,1);
//        }else {
//            todaySignUpCount.put(type,todaySignUpCount.get(type)+1);
//        }
//    }

    /**
     * 获取当前所在房间的详细信息
     */
    public int getRoomDetail(FlowerStudyProto.FlowerStudyExamRoomNewestDataReq req){
        int simpleCheck = simpleCheck(req.getActivityId());
        if (simpleCheck!=0){
            return simpleCheck;
        }
        player.sendPacket(CrossProtocol.C_FLOWER_STUDY_EXAM_GET_ROOM_DETAIL, req.toBuilder());
        return 0;
    }

    /**
     * 取消匹配
     * @param req
     * @return
     */

    public int cancelMatching(FlowerStudyProto.FlowerStudyExamMatchingCancelReq req){
        int simpleCheck = simpleCheck(req.getActivityId());
        if (simpleCheck!=0){
            return simpleCheck;
        }
        player.sendPacket(CrossProtocol.C_FLOWER_STUDY_EXAM_CANCEL_MATCHING, req.toBuilder());
        return 0;
    }

    /**
     *  提前交卷
     * @param req
     * @return
     */

    public int submitAdvance(FlowerStudyProto.FlowerStudyExamSubmitAdvanceReq req){
        int simpleCheck = simpleCheck(req.getActivityId());
        if (simpleCheck!=0){
            return simpleCheck;
        }
        player.sendPacket(CrossProtocol.C_FLOWER_STUDY_EXAM_SUBMIT_ADVANCE,req.toBuilder());
        return 0;
    }

    /**
     * 获取跨服数据
     * @param req
     * @return
     */

    public int getCrossData(FlowerStudyProto.FlowerStudyUserCrossExamDataReq req){
        int simpleCheck = simpleCheck(req.getActivityId());
        if (simpleCheck!=0){
            return simpleCheck;
        }
        FlowerStudyProto.FlowerStudyUserCrossExamDataReq.Builder builder = req.toBuilder();
        builder.setLanguage(player.getLanguage());
        player.sendPacket(CrossProtocol.C_FLOWER_STUDY_GET_CROSS_USER_DATA, builder);
        return 0;
    }

    /**
     * 处理跨服返回的玩家数据
     */
    public void dealCrossUserDataResult(FlowerStudyProto.getUserCrossDataToServerResp resp){
        FlowerStudyProto.FlowerStudyUserCrossExamDataResp.Builder builder = FlowerStudyProto.FlowerStudyUserCrossExamDataResp.newBuilder();
        if (resp.getRet() != 0){
            builder.setRet(resp.getRet());
            player.sendPacket(ClientProtocol.U_FLOWER_STUDY_GET_CROSS_EXAM_DATA,builder);
            return;
        }
        builder.setRet(0);
        FlowerStudyProto.CrossFlowerStudyUserData crossUserData = resp.getCrossUserData();
        updateRank(crossUserData);
        FlowerStudyProto.FlowerStudyExamUserDataMsg.Builder dataBuilder = FlowerStudyProto.FlowerStudyExamUserDataMsg.newBuilder();
        dataBuilder.addAllJoinTime(crossUserData.getJoinTimeList());
        dataBuilder.setHasSignUpLevel(crossUserData.getHasSignUpLevel());
        dataBuilder.setRoomId(crossUserData.getRoomId());
        builder.setCrossUserData(dataBuilder);
        player.sendPacket(ClientProtocol.U_FLOWER_STUDY_GET_CROSS_EXAM_DATA,builder);
    }


    /**
     * 更新排行榜
     * @param crossUserData
     */
    public void updateRank(FlowerStudyProto.CrossFlowerStudyUserData crossUserData){
        ActivityInfo activityInfo = FlowerStudyMgr.getActivityInfo();
        if (activityInfo == null){
            return;
        }
        if (crossUserData.getActivityId() != activityInfo.getActivityId()){
            return;
        }
        FlowerStudyRankArgs localArg = new FlowerStudyRankArgs(crossUserData.getLocalScore(),crossUserData.getLocalTime());
        FlowerStudyRankArgs provinceArg = new FlowerStudyRankArgs(crossUserData.getProvinceScore(),crossUserData.getProvinceTime());
        FlowerStudyRankArgs palaceArg = new FlowerStudyRankArgs(crossUserData.getPalaceScore(),crossUserData.getPalaceTime());

        player.notifyListener(eGamePlayerEventType.FlowerStudyScoreLocalRankCondition.getValue(), localArg);
        player.notifyListener(eGamePlayerEventType.FlowerStudyScoreProvinceRankCondition.getValue(), provinceArg);
        player.notifyListener(eGamePlayerEventType.FlowerStudyScorePalaceRankCondition.getValue(), palaceArg);
    }

    public int getReport(int activityId){
        int simpleCheck = simpleCheck(activityId);
        if (simpleCheck!=0){
            return simpleCheck;
        }
        FlowerStudyProto.getFlowerStudyExamBattleReportResp.Builder builder = FlowerStudyProto.getFlowerStudyExamBattleReportResp.newBuilder();
        builder.setRet(0);
        for (FlowerStudyUserWarReport report:reportList){
            FlowerStudyProto.FlowerStudyExamBattleReportMsg.Builder parseReportToMsg = parseReportToMsg(report);
            builder.addBattleReport(parseReportToMsg);
        }
        player.sendPacket(ClientProtocol.U_FLOWER_STUDY_GET_WAR_REPORT,builder);
        return 0;
    }

    public FlowerStudyProto.FlowerStudyExamBattleReportMsg.Builder parseReportToMsg(FlowerStudyUserWarReport report){
        FlowerStudyProto.FlowerStudyExamBattleReportMsg.Builder builder = FlowerStudyProto.FlowerStudyExamBattleReportMsg.newBuilder();
        builder.setRoomId(report.getRoomId());
        builder.setRoomType(report.getRoomType());
        builder.setScore(report.getScore());
        builder.setUseTime(report.getAnswerTime());
        builder.setRank(report.getRank());
        builder.setReward(report.getReward());
        builder.setTime(report.getSettlementTime());
        return builder;
    }


}
